﻿using GatewayServerService.Mq;
using Models.Common;
using Models.Device;
using Models.JsonResultModel;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using UtilsORM;
using UtilsORM.MySqlData;
using Models.Constant;

////using System.Web.Script.Serialization;

namespace GatewayServerService.CloudCenter
{
    public class ServiceCloodAPIControl_ext
    {
        public bool upGradeMQTTConfig(MQTTInfo mQTT, string gwcode)
        {


            //验证一下是否通的接口
            try
            {
                ConnectionFactory factory = new ConnectionFactory
                {
                    UserName = mQTT.UserName,// "notifier",//用户名
                    Password = mQTT.Password,// "bjxNx6HSok",//密码
                    HostName = mQTT.HostName,// "192.168.197.217",//rabbitmq ip
                    Port = mQTT.Port,//  5672,
                    VirtualHost = mQTT.VirtualHost,//  "notifier"
                };
                //创建连接
                var connection = factory.CreateConnection();
            }
            catch (Exception ex)
            {
                //连接报错 返回
                Console.WriteLine("新的mq不正确，无法连接,退出更新");
                return false;// RespResult.Faild("新的mq不正确，无法连接,退出更新");
            }
            string sql = "select  * from  iot_device_gateway where gw_code='" + gwcode + "'";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            List<UpgradeSoftWareModel> JiDianQiApiModels = new List<UpgradeSoftWareModel>();
            foreach (DataRow dr in dt.Rows)
            {
                MQReqModel<object> mQReqModel = new MQReqModel<object>();
                mQReqModel.respEvent = MQEventEnum.Device_Gateway_MQTTInfo;// "mqinfo";
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.gatewayCode = dr["gw_code"].ToString();
                mQReqModel.gatewayDeviceGuid = dr["gw_d_guid"].ToString();
                mQReqModel.data = mQTT;
                mQReqModel.guid = Guid.NewGuid().ToString();
                new ServiceSendMQ().sendMsg(MQEventEnum.MQDevice_gatewayServer_QueueName + mQReqModel.gatewayCode, mQReqModel);
            }
            return true;
        }
        public bool upConfigAppSetting(ModelConfigKeyValue modelConfig, string gwcode)
        {
            string sql = "select  * from  iot_device_gateway where gw_code='" + gwcode + "'";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            foreach (DataRow dr in dt.Rows)
            {
                MQReqModel<object> mQReqModel = new MQReqModel<object>();
                mQReqModel.respEvent = MQEventEnum.Device_Gateway_UpdateConfig_Value;// "mqinfo";
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.gatewayCode = dr["gw_code"].ToString();
                mQReqModel.gatewayDeviceGuid = dr["gw_d_guid"].ToString();
                mQReqModel.data = modelConfig;
                mQReqModel.guid = Guid.NewGuid().ToString();
                new ServiceSendMQ().sendMsg(MQEventEnum.MQDevice_gatewayServer_QueueName + mQReqModel.gatewayCode, mQReqModel);
            }
            return true;
        }

        /// <summary>
        /// 发送原始指令
        /// </summary>
        /// <param name="content"></param>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public string sendBashCommand(string content, string gwcode)
        {
            string sql = "select * from iot_device_gateway  where gw_code='" + gwcode + "'";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                MQSystemCommand mQSystemCommand = new MQSystemCommand();
                mQSystemCommand.guid = Guid.NewGuid().ToString();
                mQSystemCommand.fileName = "/bin/bash";
                mQSystemCommand.command = content;

                MQReqModel<object> mQReqModel = new MQReqModel<object>();
                mQReqModel.respEvent = MQEventEnum.Device_Command;
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.gatewayCode = dt.Rows[0]["gw_code"].ToString();
                mQReqModel.gatewayDeviceGuid = dt.Rows[0]["gw_d_guid"].ToString();
                mQReqModel.data = mQSystemCommand;
                mQReqModel.guid = Guid.NewGuid().ToString();
                new ServiceSendMQ().sendMsg(MQEventEnum.MQDevice_gatewayServer_QueueName + mQReqModel.gatewayCode, mQReqModel);

                Console.WriteLine("command:" + content + "执行完成");
                sql = "INSERT INTO  iot_device_minimachinecommand_log (c_d_guid,c_gw_code, c_deviceid, c_add_time,c_guid, c_status, c_gw_guid, c_return_msg, c_command)";
                sql = sql + " VALUES ( '" + dt.Rows[0]["gw_d_guid"].ToString() + "','" + gwcode + "','" + dt.Rows[0]["gw_deviceid"].ToString() + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', '" + mQSystemCommand.guid + "', 0, '" + dt.Rows[0]["gw_guid"] + "', NULL, @command);";
                new MySqlYihongIot().Db.Ado.ExecuteCommand(sql, new { mQSystemCommand.command });
                // Thread.Sleep(2000);


            }
            return "";
        }


        public void updateGradeSoftware(string gwcode)
        {
            EFYihongIotContext ef = new EFYihongIotContext();

            iot_device_gateway gwmodel = ef.iot_device_gateway.Where(c => c.gw_code == gwcode).FirstOrDefault();

            string sql = @"INSERT INTO iot_device_software (sw_guid, sw_gw_guid, sw_status, sw_command, sw_service_name, sw_packages_url, sw_mod_time, sw_add_time, sw_version,sw_swp_guid) 
                select  '" + Guid.NewGuid() + "','" + gwmodel.gw_guid + "',0, swp_command, swp_service_name, swp_packages_url,'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' , swp_version,swp_guid from iot_device_software_publish where swp_status=0 order by swp_id desc limit 1 ";
            new MySqlYihongIot().Db.Ado.ExecuteCommand(sql);
            sql = "select  * from iot_device_software inner join iot_device_gateway on sw_gw_guid=gw_guid where sw_status=0  and gw_code='" + gwcode + "'";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            UpgradeSoftWareModel upgradeSoftWareModel = null;
            foreach (DataRow dr in dt.Rows)
            {

                upgradeSoftWareModel = new UpgradeSoftWareModel();
                upgradeSoftWareModel.guid = dr["sw_guid"].ToString();
                upgradeSoftWareModel.command = dr["sW_Command"].ToString();
                upgradeSoftWareModel.serviceName = dr["sw_service_name"].ToString();
                upgradeSoftWareModel.packagesUrl = dr["sw_packages_url"].ToString();
                sql = "update  iot_device_software set sw_status=1,sw_return_msg='处理中',sw_mod_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where sw_guid='" + upgradeSoftWareModel.guid + "' and sw_status=0 ";
                MySqlYihongIot.ExecuteCommand(sql);

                //推送
                MQReqModel<object> mQReqModel = new MQReqModel<object>();
                mQReqModel.respEvent = MQEventEnum.Device_Gateway_SoftWareUpgrade;
                mQReqModel.respCode = ResponseCode.SUCCESS;
                mQReqModel.gatewayCode = dr["gw_code"].ToString();
                mQReqModel.gatewayDeviceGuid = dr["gw_d_guid"].ToString();
                mQReqModel.data = upgradeSoftWareModel;
                mQReqModel.guid = Guid.NewGuid().ToString();
                bool result = new ServiceSendMQ().sendMsg(MQEventEnum.MQDevice_gatewayUpdateServer_QueueName + dr["gw_code"].ToString(), mQReqModel, ConstantAppName.gateway_upgrade);

            }
        }

    }
}
